from os import spawnl, P_NOWAIT, WNOHANG
from os import kill as send_signal
from os import waitpid as waitForProcessExit

from signal import SIGKILL as theKillSignal
from signal import SIGSTOP as thePauseSignal
from signal import SIGCONT as theResumeSignal
from signal import SIGCHLD as theReapSignal

from signal import signal as installSignalHandler

from select import error as SelectError
from errno import EINTR, ECHILD

def isInterruptError(e):
    return (e.args[0] == EINTR)
def isReapComplete(e):
    return (e.args[0] == ECHILD)

class NativePlatform:
    def __init__(self, config):
        self.wgetbin = config.wgetbin
        installSignalHandler(theReapSignal, self.reap)

    def reap(self, signr, stack_frame):
        if signr == theReapSignal:
            for (pid, status) in cleanupChildProcesses():
                pass

    def cleanupChildProcesses(self):
        while True:
            try: (pid, status) = waitForProcessExit(-1, WNOHANG)
            except OSError, e:
                if isReapComplete(e):
                    break

                reraise()

            yield (pid, status >> 8)

    # Not really needed, since using spawn*
    ##    def safe_shell_string(self, string):
    ##        return "'%s'" % string

    def spawn_download(self, kwd):
        args = ['-c', kwd['url']]
        if 'filename' in kwd:
            args.append('-O')
            args.append(kwd['filename'])

        return spawnl(P_NOWAIT, self.wgetbin, *args)

    def kill_download(self, pid):
        send_signal(pid, theKillSignal)
    def pause_download(self, pid):
        send_signal(pid, thePauseSignal)
    def resume_download(self, pid):
        send_signal(pid, theResumeSignal)
